import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 87111
 * Date: 2025-11-18
 * Time: 19:52
 */
public class UdpEchoClient {
    //发送请求
    private DatagramSocket socket = null;
    //这里要存储目的IP和目的端口
    private String serverIP;
    private int serverPort;

    //此处构造方法需要指定目的IP和目的端口号
    public UdpEchoClient(String serverIP,int port) throws SocketException {
        this.serverIP = serverIP;
        this.serverPort = port;
        //客户端使用随机端口
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        Scanner sc = new Scanner(System.in);
        while(true) {
            System.out.println("请输入要翻译的词:");
            String request = sc.next();
            //根据输入，构造请求数据包
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,
                    request.getBytes().length, InetAddress.getByName(serverIP),serverPort);
            //将请求数据包发送出去
            socket.send(requestPacket);

            //接收响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[5096],0,5096);
            socket.receive(responsePacket);
            //打印响应
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
